package com.twf.partnerMatching.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.twf.partnerMatching.common.BaseResponse;
import com.twf.partnerMatching.common.utils.ResultUtils;
import com.twf.partnerMatching.exception.BusinessException;
import com.twf.partnerMatching.model.domain.User;
import com.twf.partnerMatching.model.request.UserLoginRequest;
import com.twf.partnerMatching.model.request.UserRegisterRequest;
import com.twf.partnerMatching.model.vo.UserClearVO;
import com.twf.partnerMatching.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

import static com.twf.partnerMatching.common.ErrorCode.*;
import static com.twf.partnerMatching.contant.UserConstant.ADMIN_ROLE;
import static com.twf.partnerMatching.contant.UserConstant.USER_LOGIN_STATE;

/**
 * @author TwfPlayer
 * @date 2023/10/8 16:16
 * @description 用户访问控制
 */
@RestController //适用与编写restful风格的API，返回默认为JSON类型
@RequestMapping("/user")
@CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(NULL_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(PARAMS_ERROR, "请求参数为空");
        }
        long id = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(id);
    }

    @PostMapping("/login")
    public BaseResponse<UserClearVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(NULL_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(PARAMS_ERROR, "请求参数为空");
        }
        UserClearVO userClearVO = userService.userLogin(userAccount, userPassword);
        //记录用户登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, userClearVO);
        return ResultUtils.success(userClearVO);
    }

    @GetMapping("/currentUser")
    public BaseResponse<UserClearVO> getCurrentUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        UserClearVO currentUser = (UserClearVO) userObj;
        if (currentUser == null) {
            throw new BusinessException(NOT_LOGIN);
        }
//        todo 校验用户是否合法 有效性等
        Long userId = currentUser.getId();
        UserClearVO safetyUser = new UserClearVO(userService.getById(userId));
        return ResultUtils.success(safetyUser);
    }

    // todo 其他查询
    @GetMapping("/search")
    public BaseResponse<List<UserClearVO>> searchUsers(String username, String userAccount, HttpServletRequest request) {
        //仅管理员可查
        if (!isAdmin(request)) {
            throw new BusinessException(NO_AUTH, "缺少管理员权限");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        if (StringUtils.isNotBlank(userAccount)) {
            queryWrapper.like("user_account", userAccount);
        }
        List<User> userlist = userService.list(queryWrapper);
        List<UserClearVO> userClearVOList = userlist.stream().map(UserClearVO::new).collect(Collectors.toList());
        return ResultUtils.success(userClearVOList);
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id, HttpServletRequest request) {
        //仅管理员可删
        if (!isAdmin(request)) {
            throw new BusinessException(NO_AUTH, "缺少管理员权限");
        }
        if (id <= 0) {
            throw new BusinessException(PARAMS_ERROR, "请求参数错误");
        }
        return ResultUtils.success(userService.removeById(id));
    }

    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(NOT_LOGIN);
        }
        //移除登录状态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return ResultUtils.success(true);
    }


    private boolean isAdmin(HttpServletRequest request) {
        //仅管理员可查
        Object userObject = request.getSession().getAttribute(USER_LOGIN_STATE);
        UserClearVO user = (UserClearVO) userObject;
        if (user == null || user.getUserRole() != ADMIN_ROLE) {
            return false;
        }
        return true;
    }


}
